﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Categories;
using NopSolutions.NopCommerce.BusinessLogic.Data;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.BusinessLogic.Products.Specs;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.LuceneHelper;

namespace NopSolutions.NopCommerce.Web.Templates.Lucene
{
    public partial class LuceneProducts : BaseNopUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                BindData();
            }
        }

        protected void SetSortBy()
        {
            //var sortBy = CommonHelper.QueryString("sortBy");
            //ddlSortBy.SelectedValue = string.IsNullOrEmpty(sortBy) ? Globals.SORTBY_RELEVANCE : sortBy;
        }

        protected void BindData()
        {
            #region Standard stuff

            SetSortBy();

            int totalRecords = 0;
            int pageSize = 20;

            var filterContext = new FilterContext(HttpContext.Current.Request.QueryString);

            var searchManager = new SearchManager();
            var productSearchResult = DoSearch(searchManager, CurrentPageIndex, pageSize,
                                                 filterContext);
            totalRecords = productSearchResult.Total;

            var products = productSearchResult.ProductDocuments.MapProducts(false);

            if (products.Count > 0)
            {
                productsPager.PageSize = pageSize;
                productsPager.TotalRecords = totalRecords;
                productsPager.PageIndex = this.CurrentPageIndex - 1;
                productsPager2.PageSize = pageSize;
                productsPager2.TotalRecords = totalRecords;
                productsPager2.PageIndex = CurrentPageIndex - 1;

                dlProducts.DataSource = products;
                dlProducts.DataBind();
            }
            else
            {
                this.dlProducts.Visible = false;
            }

            #endregion

            var priceRangeValues = searchManager.GetPriceRanges(productSearchResult.Query);

            var facets = searchManager.GetFacetsOnProductQuery(filterContext, productSearchResult.Query);

            #region Category facets

            var categoryFacets = new List<CategoryValue>();

            if (filterContext.Categories.Count > 0)
            {
                var children = new List<Category>();
                foreach (var cid in filterContext.Categories)
                {
                    foreach (var child in CategoryManager.GetAllCategoriesByParentCategoryId(cid))
                    {
                        var tcid = child.CategoryId;
                        if (!children.Any(x => x.CategoryId == tcid))
                        {
                            children.Add(child);
                        }
                    }
                }
                categoryFacets.AddRange(searchManager.SearchForCategoriesOnProductQuery(productSearchResult.Query,
                                                                                        children));
            }

            #endregion




            var filterEventArgs = new FilterEventArgs(productSearchResult, facets,
                filterContext.Manufacturers, priceRangeValues, filterContext, categoryFacets);

            LuceneContext.Instance.OnLoadFilters(filterEventArgs);
        }

        private ProductSearchResult DoSearch(SearchManager searchManager, int pageNumber, int pageSize, FilterContext context)
        {
            var pagedLowerBound = pageNumber * pageSize;
            var pagedUpperBound = pagedLowerBound + pageSize;
            var result = searchManager.SearchProducts(context, pagedLowerBound, pagedUpperBound);
            return result;
        }

        public int CurrentPageIndex
        {
            get
            {
                int _pageIndex = CommonHelper.QueryStringInt(productsPager.QueryStringProperty);
                _pageIndex--;
                if (_pageIndex < 0)
                    _pageIndex = 0;
                return _pageIndex;

            }
        }

        public int CategoryID
        {
            get
            {
                return CommonHelper.QueryStringInt("CategoryID");
            }
        }

        public event EventHandler<FilterEventArgs> LoadFilters;


        protected List<PriceRange> GetPriceRangeList(Category category)
        {
            var _priceRanges = new List<PriceRange>();
            if (string.IsNullOrEmpty(category.PriceRanges))
                return _priceRanges;
            string[] rangeArray = category.PriceRanges.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string str1 in rangeArray)
            {
                string[] _fromTo = str1.Trim().Split(new char[] { '-' });

                decimal? _from = null;
                if (!String.IsNullOrEmpty(_fromTo[0]) && !String.IsNullOrEmpty(_fromTo[0].Trim()))
                {
                    _from = decimal.Parse(_fromTo[0].Trim(), new CultureInfo("en-US"));
                }
                decimal? _to = null;
                if (!String.IsNullOrEmpty(_fromTo[1]) && !String.IsNullOrEmpty(_fromTo[1].Trim()))
                {
                    _to = decimal.Parse(_fromTo[1].Trim(), new CultureInfo("en-US"));
                }
                _priceRanges.Add(new PriceRange() { From = _from, To = _to });
            }
            return _priceRanges;
        }
    }
}